require("Scene/SceneLogic")
local Scene = BaseClass(Singleton)


function Scene:__init()
    local cube=CS.UtilsCSharp.LoadAssetData_Game("cube")
    GameObject.Instantiate(cube)
    -- 注册所有需要响应的协议
    self:RegisterAllEvents() -- 注册所有需要监听的事件
    
end

function Scene:RegisterAllEvents()

end

function Scene:__delete()

end

function Scene:ClearScene()
    if nil ~= self.scene_logic then
        self.scene_logic:DeleteMe()
        self.scene_logic = nil
    end
end

function Scene:Update(detaTime)
    if nil ~= self.scene_logic then
        self.scene_logic:Update(detaTime)
        
    end
end

function Scene:OnChangeScene(scene_id)
    local scene_config = GetConfig("scene_"..scene_id)
   print(scene_id.."-----")

    if nil == scene_config then
        --print_log("scene_config not find, scene_id:" .. scene_id)
        return
    end
    print(scene_config.name.."-----")
    if self.scene_logic ~= nil then
        self.scene_logic:Out(scene_config.scene_type)
    end

    self:ClearScene()

    self.scene_config = scene_config

    self.scene_logic = SceneLogic.Create(self.scene_config.scene_type)
    self.scene_logic:Enter(nil)
    --self:StartLoadScene(  self.scene_config .asset_name, BindTool.Bind(self.OnLoadSceneComplete, self))
end

-- 打开加载条加载场景
function Scene:StartLoadScene(scene_id, onComplete)
    -- 启动协程执行加载流程
    local co = xluaUtil.cs_generator(function()
        local asyncOp = SceneManager.LoadSceneAsync(scene_id)
        asyncOp.allowSceneActivation = false



        local progress = Mathf.CeilToInt((asyncOp.progress * 100))
        while progress < 90 do
            
            coroutine.yield(WaitForSeconds(0.1))
            progress = Mathf.CeilToInt((asyncOp.progress * 100))
            -- print(progress)
        end

        while progress >= 90 and progress <= 99 do
            progress = progress + 1
            coroutine.yield(WaitForSeconds(0.2))
            -- print("ssss:" .. progress)
        end
        
        asyncOp.allowSceneActivation = true

        -- 等待完成
        while not asyncOp.isDone do
            coroutine.yield(0)
        end
        
        -- 执行回调
        if onComplete then
            onComplete()
        end
    end)

    local runner = GameObject.Find("Coroutine_Runner")
    if not runner then
        runner = GameObject("Coroutine_Runner")
        --UnityEngine.Object.DontDestroyOnLoad(runner)
        runner:AddComponent(typeof(Coroutine_Runner))
    end
    -- 启动协程
    runner:GetComponent(typeof(Coroutine_Runner)):StartCoroutine(co)
end

-- 场景卸载逻辑
function Scene:UnloadCurrentScene()
    -- 执行场景清理逻辑
    CS.UnityEngine.Resources.UnloadUnusedAssets()
    collectgarbage("collect")
end

function Scene:OnLoadSceneComplete()
    self.scene_logic:Enter(nil)
end

return Scene
